#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
  printf("I am a parent process,pid:%d,ppid:%d\n",getpid(),getppid());
  
  pid_t id = fork();
  if(id < 0)
  {
    exit(1);
  }

  else if(id == 0)
  {
    int cnt = 5;
    while(cnt--)
    {
      printf("I am a child process,pid:%d,ppid:%d\n",getpid(),getppid());
      sleep(1);
    }
    exit(10);
  }

  else{
		while(1)
		{
			int status = 0;                                                                                                                                                              
      pid_t rid = waitpid(id, &status, WNOHANG); //非阻塞检测 && 回收    
      if(rid > 0)          
      {                                                                      
        printf("wait success,退出的子进程是:%d,exit_code:%d\n",rid,WEXITSTATUS(status));    
      }    
      else if(rid == 0)    
      {    
        printf("子进程正在运行，父进程需要等待\n");    
        usleep(100000);
      }        
      else{    
        perror("waitpid");    
        break;
      }    
		}
  }

  return 0;
}
